<template>
  <!-- 文章管理 -->
  <div class="wrapper">
    <a-card :body-style="{ padding: 0 }" :bordered="false">
      <div class="table-page-search-wrapper" style="margin-bottom: 16px">
        <a-row style="margin-bottom: 16px">
          <a-col :md="20" :sm="24">
            <SearchForm :query="queryParam" @onSearch="initData" />
          </a-col>
          <a-col :md="4" :sm="24" style="text-align: right">
            <a-button type="primary" class="actionButton" @click="add">添加</a-button>
            <a-popconfirm title="确定删除?" okText="确定" cancelText="取消" @confirm="del">
              <a-button type="danger" class="actionButton">删除</a-button>
            </a-popconfirm>
          </a-col>
        </a-row>
      </div>
      <a-spin :indicator="indicator" :spinning="spinning" tip="获取数据中...">
        <div class="spin-content">
          <a-table size="small" bordered :rowKey="(record) => record.id" :columns="columns" :dataSource="data" :pagination="pagination" :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }" :rowClassName="setRowClassName">
            <span slot="action" slot-scope="text, record">
              <template>
                <a size="small" type="link" @click="handleView(record)">查看</a>
                <a-divider type="vertical" />
                <a size="small" type="link" @click="handleEdit(record)">修改</a>
              </template>
            </span>
          </a-table>
        </div>
      </a-spin>
    </a-card>

    <a-modal :title="title" :visible="visibleDetail" :width="400" @cancel="visibleDetail = false" :footer="null" :centered="true">
      <div>
        <a-form :form="form">
          <a-form-item v-bind="formItemLayout" label="文章标题">
            {{ formDetail.Title }}
          </a-form-item>
          <a-form-item v-bind="formItemLayout" label="类别类型">
            {{ formDetail.CategoryTypeName }}
          </a-form-item>
          <a-form-item v-bind="formItemLayout" label="是否发布">
            {{ formDetail.isSend }}
          </a-form-item>
          <!-- <a-form-item v-bind="formItemLayout" label="附件">

          </a-form-item> -->
          <a-form-item v-bind="formItemLayout" label="标题图片">
            <img style="height: 104px; width: 100px" :src="formDetail.TitleImage" alt="avatar" />
          </a-form-item>
          <a-form-item v-bind="formItemLayout" label="文章内容">
            <!-- 富文本 -->
            <div v-html="formDetail.Context"></div>
          </a-form-item>

          <a-form-item v-bind="formItemLayout1" style="text-align: center; margin-bottom: 0">
            <a-button type="primary" @click="visibleDetail = false">关闭</a-button>
          </a-form-item>
        </a-form>
      </div>
    </a-modal>

    <a-modal :title="title" :visible="visible" :width="900" @cancel="visible = false" :footer="null" :centered="true">
      <div class="waterArea" style="background-color: #fff">
        <a-spin :spinning="loading">
          <a-form :form="form">
            <a-form-item v-bind="formItemLayout" label="文章标题">
              <a-input v-decorator="['Title', { rules: [{ required: true, message: '请填写文章标题!' }] }]" />
            </a-form-item>
            <a-form-item v-bind="formItemLayout" label="类别类型">
              <treeselect :show-count="true" :options="CategoryTypeList" v-model="CategoryTypeID" placeholder="请选择" :normalizer="normalizer" />
              <!-- <a-select v-decorator="['CategoryTypeID', { rules: [{ required: true, message: '请选择类别类型!' }] }]" size="small" style="width: 100%">
                <a-select-option v-for="item in CategoryTypeList" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
              </a-select> -->
              <!-- <a-input v-decorator="['CategoryType', { rules: [{ required: true, message: '请填写部门名称!' }] }]" /> -->
            </a-form-item>
            <a-form-item v-bind="formItemLayout" label="是否发布">
              <a-select v-decorator="['isSend', { rules: [{ required: true, message: '请选择是否发布!' }] }]" size="small" style="width: 100%">
                <a-select-option :value="1">是</a-select-option>
                <a-select-option :value="0">否</a-select-option>
              </a-select>
              <!-- <a-input v-decorator="['CategoryType', { rules: [{ required: true, message: '请填写部门名称!' }] }]" /> -->
            </a-form-item>
            <a-form-item v-bind="formItemLayout" label="附件">
              <a-upload :action="uploarUrl" :headers="headers" :fileList="fileList" @change="handleChange">
             
                <a-button type="primary" :loading="btnloading"> 上传 </a-button>
              </a-upload>
            </a-form-item>
            <a-form-item v-bind="formItemLayout" label="标题图片">
              <!-- <a-input v-decorator="['TitleImage', { rules: [{ required: true, message: '链接URL!' }] }]" /> -->
              <a-upload name="avatar" listType="picture-card" class="avatar-uploader" :showUploadList="false" :action="uploarUrlImage" :headers="headers" :beforeUpload="beforePhotoUpload" @change="handlePhotoChange">
                <a-popover placement="right">
                  <template slot="content">
                    <a-button @click="removePhotoUrl" type="danger" size="small">删除</a-button>
                    <a-button @click="viewPhoto(1)" type="primary" style="margin-left: 5px" size="small">查看大图</a-button>
                  </template>
                  <img v-if="PhotoUrl" style="height: 104px" :src="PhotoUrl" alt="avatar" />
                </a-popover>
                <div v-if="!PhotoUrl">
                  <a-icon :type="Photoloading ? 'loading' : 'plus'" />
                  <div class="ant-upload-text">图片上传</div>
                </div>
              </a-upload>
            </a-form-item>
            <a-form-item v-bind="formItemLayout" label="文章内容">
              <!-- 富文本 -->
              <Editor :value="content" @getEditor="handleGetEditor" />
              <!-- <a-textarea :rows="4" v-decorator="['Context']" /> -->
            </a-form-item>

            <a-form-item v-bind="formItemLayout1" style="text-align: center; margin-bottom: 0">
              <a-button type="primary" @click="ok">确定</a-button>
            </a-form-item>
          </a-form>
        </a-spin>
      </div>
    </a-modal>
    <photo-modal ref="photomodal"></photo-modal>
  </div>
</template>

<script>
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { getCategoryTree } from '@/api/category'
import SearchForm from './modules/searchform'

import { getContextsList, getDetailByCategoryID, saveContexts, getDetailByID, deleteontexts } from '@/api/article'
import { mapActions, mapGetters } from 'vuex'
import { tranDate, typleFilter } from '@/utils/util'
import Editor from '@/components/Editor/Editor.vue'
import PhotoModal from '@/views/photoModal'
import { getImg } from '@/api/students'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import '@/views/treeselect1.css'

import { message } from 'ant-design-vue'

const userInfo = Vue.ls.get(ACCESS_TOKEN) // DepartmentID
let columnsData = [
  {
    title: '文章标题',
    dataIndex: 'Title',
    key: 'Title',
    align: 'center',
  },
  // {
  //   title: '标题图片',
  //   dataIndex: 'TitleImage',
  //   key: 'TitleImage',
  //   align: 'center',
  // },
  {
    title: '类别类型',
    dataIndex: 'CategoryTypeName',
    key: 'CategoryTypeName',
    align: 'center',
  },
  {
    title: '查看次数',
    dataIndex: 'ViewCount',
    key: 'ViewCount',
    align: 'center',
  },
  {
    title: '是否发布',
    dataIndex: 'isSend',
    key: 'isSend',
    align: 'center',
  },
  {
    title: '操作',
    width: '150px',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' },
    align: 'center',
  },
]
export default {
  components: { Editor, PhotoModal, Treeselect, SearchForm },
  props: {
    display: {
      type: String,
      required: false,
      default: 'default',
    },
  },
  created() {
    this.getTypeList()
    this.initData(this.queryParam)
    const token = Vue.ls.get(ACCESS_TOKEN) && Vue.ls.get(ACCESS_TOKEN).token
    this.headers = {
      authorization: 'Bearer ' + token,
    }
  },
  mounted() {},
  data() {
    return {
      title: '添加文章',
      visible: false,
      visibleDetail: false,
      columnsData,
      action: 'add',
      indicator: <a-icon type="loading" style="font-size: 24px" spin />,
      spinning: false,
      data: [],
      form: this.$form.createForm(this),
      formDetail: {},
      queryParam: {
        index: 1,
        pageSize: 10,
      },
      normalizer(node) {
        return {
          id: node.id,
          label: node.CategoryName,
          children: node.Children,
        }
      },
      CategoryTypeID: '',
      content: '',
      btnloading: false,
      Photoloading: false,
      PhotoUrl: '',
      PhotoUrl: '',
      PhotoUrlDb: {},
      PhotoUrlDbString: '',
      headers: {
        authorization: '',
      },
      uploarUrl: process.env.VUE_APP_API_BASE_URL + `/api/Upload/uploadImg?tablename=Contexts&signname=Annex`,
      uploarUrlImage: process.env.VUE_APP_API_BASE_URL + `/api/Upload/uploadImg?tablename=StudentInfo&signname=Photo`,
      fileList: [],
      CategoryTypeList: [],
      selectedRowKeys: [],
      pagination: {
        onChange: (index, pageSize) => {
          this.pageOnChange(index, pageSize)
        },
        current: 1,
        total: 0,
        showQuickJumper: true,
        size: 'small',
        defaultPageSize: 10,
        showTotal: (total) => `共 ${total} 条数据`,
        showSizeChanger: true,
        pageSizeOptions: ['5', '10', '15', '20'],
        onShowSizeChange: (index, pageSize) => {
          this.pageOnChange(index, pageSize)
        },
        position: 'bottom',
      },
      allPersonNum: 0,
      userInfoData: userInfo,
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 18 },
        },
      },
      formItemLayout1: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 0 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 },
        },
      },
      loading: false,
      currentId: null,
    }
  },
  watch: {},
  computed: {
    ...mapGetters(['token']),
    columns() {
      return this.columnsData
    },
  },
  methods: {
    initData(data) {
      this.spinning = true
      console.log(data)
      getContextsList(data)
        .then((res) => {
          this.data = res.data
          this.data.map((a) => {
            a.startDate = tranDate(a.startDate)
            a.endDate = tranDate(a.endDate)
            a.isSend = a.isSend === true ? '是' : '否'
          })
          this.pagination.total = res.page.RecordCount
        })
        .finally(() => {
          this.spinning = false
        })
    },
    search(data) {
      Object.assign(this.queryParam, data, { index: 1 })
      this.pagination.current = 1
      this.initData(this.queryParam)
    },
    async getTypeList() {
      const { data } = await getCategoryTree()
      this.CategoryTypeList = data
    },
    handleGetEditor(data) {
      this.content = data
    },
    handleChange({ file, fileList }) {
      if (file.status !== 'uploading') {
        this.btnloading = true
      }
      if (file.status === 'done') {
        console.log('上传成功')
        this.btnloading = false
      }
      console.log(file, fileList)
      this.fileList = fileList
    },
    del() {
      let _this = this
      console.log(!(this.selectedRowKeys && this.selectedRowKeys.length > 0))
      if (!(this.selectedRowKeys && this.selectedRowKeys.length > 0)) {
        _this.$message.error('请选择数据')
        return
      }
      deleteontexts(this.selectedRowKeys).then((res) => {
        this.initData(this.queryParam)
        this.selectedRowKeys = []
      })
    },

    add() {
      this.title = '添加文章'
      this.visible = true
      this.content = ''
      this.PhotoUrl = ''
      this.form.resetFields()
      this.handleCancel()
    },
    handleEdit(data) {
      this.title = '修改文章'
      getDetailByID({ contextsID: data.id }).then((res) => {
        this.visible = true
        console.log(res,'res')
        setTimeout(() => {
          this.currentId = res.data.id
          this.CategoryTypeID = data.CategoryTypeID
          this.content = res.data.Context
          this.PhotoUrl = res.data.TitleImage
          console.log( res.data.Annexs,data,'ffffggggggg')
          this.fileList = res.data.Annexs && res.data.Annexs.length>0 ? res.data.Annexs.map((el,index)=>{
            return {
              ...el,
              uid: `${index}${el.ID}`,
              name: el.OldFileName
            }
          }):[]
          this.form.setFieldsValue({ ...res.data })
        }, 500)
      })
    },

    handleView(data) {
      this.title = '查看文章'
      this.visibleDetail = true
      setTimeout(() => {
        this.formDetail = {
          ...data,
          isSend: data.isSend === true ? '是' : '否',
        }
      }, 500)
    },

    ok() {
      const {
        form: { validateFields },
      } = this
      validateFields((errors, values) => {
        if (!errors) {
          this.loading = true
          setTimeout(() => {
            // console.log(this.$store.getters.token.id)
            const value = {
              ...values,
              isSend: values.isSend == 1 ? true : false,
              Context: this.content || '',
              Id: this.currentId,
              Annexs: this.fileList && this.fileList.length > 0 ? this.fileList.map(el=>{return el.response}) : [],
              TitleImage: this.PhotoUrl,
              CategoryTypeID: this.CategoryTypeID,
            }
            saveContexts(value).then((res) => {
              this.initData(this.queryParam)
              this.loading = false
              this.visible = false
              // this.handleCancel()
            })
          }, 1000)
        } else {
        }
      })
    },

    /** 关闭弹框 */
    handleCancel() {
      this.currentId = null
      this.fileList = []
      this.PhotoUrl = ''
      this.content = ''
      this.CategoryTypeID = ''
    },

    setRowClassName(record, idx) {
      const trClass = record.LineColor === 'red' ? 'tr-red' : 'tr-p'
      const idxClass = idx % 2 === 1 ? 'bg-zebra-pattern' : ''
      return `${trClass} ${idxClass}`
    },
    onSelectChange(selectedRowKeys) {
      // console.log('selectedRowKeys changed: ', selectedRowKeys)
      this.selectedRowKeys = selectedRowKeys
    },
    pageOnChange(index, pageSize) {
      this.spinning = true
      Object.assign(this.pagination, {
        current: index,
        pageSize,
        index,
      })
      Object.assign(this.queryParam, {
        pageSize,
        index,
      })
      this.initData(this.queryParam)
    },
    viewPhoto(data) {
      this.$refs.photomodal.view(this.PhotoUrl)
    },
    beforePhotoUpload(file) {
      const token = Vue.ls.get(ACCESS_TOKEN) && Vue.ls.get(ACCESS_TOKEN).token
      this.headers = {
        authorization: 'Bearer ' + token,
      }
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        this.$message.error('您只能上传JPG或PNG!')
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('必须小于2MB!')
      }
      // console.log('')
      return isJpgOrPng && isLt2M
    },
    handlePhotoChange(info) {
      if (info.file.status === 'error') {
        this.$message.error(`上传失败`)
      }
      if (info.file.status === 'uploading') {
        this.Photoloading = true
        return
      }
      if (info.file.status === 'done') {
        this.PhotoUrlDb = info.file.response
        this.PhotoUrl = getImg(`${this.PhotoUrlDb.Path}/${this.PhotoUrlDb.NewFileName}`)
        this.PhotoUrlDbString = `${this.PhotoUrlDb.Path}/${this.PhotoUrlDb.NewFileName}`
        this.Photoloading = false
      }
    },
    removePhotoUrl() {
      this.PhotoUrl = null
      this.PhotoUrlDb = null
      this.PhotoUrlDbString = null
    },
  },
}
</script>
<style lang="less" scoped>
.actionButton {
  margin-right: 10px;
}
.wrapper {
  /deep/ .ant-badge-status-dot {
    width: 14px;
    height: 14px;
  }
}

.disable {
  pointer-events: none;
}
</style>
<style>
.tr-red {
  color: red;
}
</style>
